package ops.view.component;

import java.awt.Toolkit;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * A {@link JTextField} that only accepts numbers as valid input.
 * Default size is 10.
 * @author flavio
 */
public class NumberField extends JTextField {

	public NumberField() {
		this(10);
	}
	
	public NumberField(Number num) {
		this(num.toString().length(), num);
	}
	
	public NumberField(int size) {
		super(new NumberDocument(size), "", size);
	}
	
	public NumberField(int size, Number num) {
		this(size, num, false);
	}
	
	public NumberField(int size, Number num, boolean limitedSize) {
		super(new NumberDocument(size), num.toString(), size);
	}
	
	private static class NumberDocument extends PlainDocument {
		
		private int size = Integer.MIN_VALUE;
		
		public NumberDocument() {
			this(Integer.MIN_VALUE);
		}
		
		public NumberDocument(int size) {
			super();
			
			this.size = size;
		}
		
		@Override
		public void insertString(int offs, String str, AttributeSet a)
			throws BadLocationException {

			if (str == null || str.equals("")) 
				return;

			for (int i = str.length()-1; i > -1; i--) {
				Character ch = str.charAt(i);
				
				if (getLength() >= size) {
					break;
				} else if (Character.isDigit(ch)) {
					super.insertString(offs, ch.toString(), a);
				} else {
					Toolkit.getDefaultToolkit().beep();
				}
			}
		}
	}
}
